<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="_updateGpioControlConfig"
      @refresh="refresh"
      :fastConfig="fastConfig"
    />
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef, watch } from 'vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { getGpioControlConfig, updateGpioControlConfig } from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'GpioControl',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}

const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 1;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 3 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
  rules: any = [],
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
      ...rules,
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const checkOptions = [
  { value: '蓝色预警', label: '蓝色预警' },
  { value: '黄色预警', label: '黄色预警' },
  { value: '橙色预警', label: '橙色预警' },
  { value: '红色预警', label: '红色预警' },
  { value: '速报', label: '速报' },
  { value: '气象', label: '气象' },
  { value: '广播', label: '广播' },
];

const items = computed<ProFormProps['items']>(() => [
  itemRender('服务配置'),
  itemObj('一路(无线广播)', 'checkboxGroup', 'gpio1Config', false, {
    options: checkOptions,
  }),
  itemObj('二路(有线功放)', 'checkboxGroup', 'gpio2Config', false, {
    options: checkOptions,
  }),
  itemObj('三路', 'checkboxGroup', 'gpio3Config', false, {
    options: checkOptions,
  }),
  itemObj('四路', 'checkboxGroup', 'gpio4Config', false, {
    options: checkOptions,
  }),
]);
console.log(
  props.pageData.gpioControlConfigsJson,
  'props.pageData.gpioControlConfigsJson',
);

const gpioType = ['gpio1Config', 'gpio2Config', 'gpio3Config', 'gpio4Config'];
props.pageData.gpioControlConfigsJson
  ? (() => {
      const config = JSON.parse(props.pageData.gpioControlConfigsJson);
      console.log(config, 'config');
      for (let i in config) {
        formState.value[i] = config[i]
          .split(',')
          .map((a, b) => {
            return a == 1 ? checkOptions[b].value : undefined;
          })
          .filter((item: any) => item != undefined);
      }
      loaded.value = true;
    })()
  : getGpioControlConfig(props.pageData.code).then((res: any) => {
      formState.value = res.data;
      formState.value.code = props.pageData.code;
      gpioType.forEach((key: any, index: any) => {
        const item = formState.value[key];
        const arr = item ? item.split(',') : [];
        formState.value[key] = arr
          .map((num: any, index: number) => {
            return num == 1 ? checkOptions[index].value : undefined;
          })
          .filter((item: any) => item != undefined);
      });
      loaded.value = true;
    });

const _updateGpioControlConfig = async (params: any) => {
  const _params: any = {};
  gpioType.forEach((key: any, index: any) => {
    const item = params[key];
    _params[key] = checkOptions
      .map((option: any) => {
        return item.includes(option.value) ? 1 : 0;
      })
      .join();
  });
  await updateGpioControlConfig({ ...params, ..._params });
};
defineExpose({
  async save() {
    const data = await formRef.value.validate();
    const params: any = {};
    gpioType.forEach((g) => {
      const item = data[g] ? data[g] : [];
      const newItem: any = [];
      checkOptions.forEach((a, b) => {
        if (item.includes(a.value)) {
          newItem[b] = 1;
        } else {
          newItem[b] = 0;
        }
      });
      params[g] = newItem.join(',');
    });
    props.pageData.gpioControlConfigsJson = JSON.stringify(params);
  },
});
</script>
